#pragma once
#include <iostream>
#include <string>
using namespace std;
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

/*负责将数据写到文件的类*/
class filelogTask
{
public:
    filelogTask(){}
    filelogTask(const string &data, const string &filename = "./log.txt")
        : _data(data), _filename(filename)
    {
    }

    void operator()()
    {
        FILE *fp = fopen(_filename.c_str(),"a+");
        if (fp == nullptr)
        {
            cerr << "open file fail..." << endl;
            exit(-1);
        }
        int n = fprintf(fp,"%s\n",_data.c_str());
        if(n < 0)
        {
            cerr << "write fata fail..." << endl;
            exit(-2);
        }
        fclose(fp);
    }

private:
    string _filename;
    string _data;
};

/*负责计算+、-、*、/、%的类
 *该类需要左操作数、右操作数、操作符构造
 *对外提供函数调用运算符重载，在外部可以表现为仿函数
 *计算过程的实现作为该类的私有成员*/
template <class T>
class culculateTask
{
public:
    culculateTask() {}
    culculateTask(const T &left, const T &right, char oper)
        : _left(left), _right(right), _oper(oper)
    {
    }

    /*对外提供一个接口，用来知道准备做什么计算*/
    string getTaskName()
    {
        string left = to_string(_left);
        string right = to_string(_right);
        string ret = left + " " + _oper + " " + right + " = ?";
        return ret;
    }

    /*提供一个函数调用运算符重载
     *注意这里将计算结果作为了返回值*/
    string operator()()
    {
        T res = calculateTask(_left, _right, _oper);
        string left = to_string(_left);
        string right = to_string(_right);
        string result = left + " " + _oper + " " + right + " = " + to_string(res);
        //cout << result << endl;
        return result;
    }

private:
    T _left;
    T _right;
    char _oper;

    /*计算的过程作为该类的私有成员*/
    T calculateTask(const T &left, const T &right, char oper)
    {
        T result = 0;
        if (oper == '+')
            result = left + right;
        else if (oper == '-')
            result = left - right;
        else if (oper == '*')
            result = left * right;
        else if (oper == '/')
        {
            if (right == 0)
            {
                cout << "不合法除法!" << endl;
                result = -1;
            }
            else
                result = left / right;
        }
        else if (oper == '%')
        {
            if (right == 0)
            {
                cout << "不合法取模!" << endl;
                result = -1;
            }
            else
                result = left % right;
        }
        return result;
    }
};
